import { getTodoList, getTodoTotal, getCurrentProcess,queryActiveTaskInfo} from '@/api/process'
import { getAllTasksByProcInst } from '@/api/indexPage'
import { getProcessParams, getBusinessTodoList, getOrgEmployeesListBy, getProcessGroupPerson } from '@/api/commons'
import { getSelfAudit } from '@/api/indexPage'

import JosnBig from 'json-bigint'
import Vue from 'vue'

/**
 * 获取当前登录用户的审批待办
 */
export async function getUserTodo({ entry = null, exit = null, filterParamsFn = null, sucessCallback = null } = {}) {
  try {
    entry && entry()
    let users = []
    const userInfo = Vue.getAcloudProvider().getUserInfo()
    // 查询参数限制权限为账号所有的岗位及登录用户id
    if (userInfo?.employee?.posts) {
      users = users.concat(userInfo.employee.posts.map(item => item.id))
    }
    users.push(userInfo.id)
    let processRes = {}
    try {
      // 获取党组织相关流程的查询参数
      processRes = await getProcessParams()
    } catch (e) {
      console.error(e)
    }
    if (processRes.data) {
      users = users.concat(processRes.data)
    }
    const requestParameters = {
      users
    }
    const auditRes = await getTodoList(filterParamsFn ? filterParamsFn(requestParameters) : requestParameters)
    sucessCallback && sucessCallback(res)
    return auditRes
  } catch (e) {
    console.error('getLoginUserTodo', e)
  } finally {
    exit && exit()
  }
}

/**
 * 获取当前登录用户的获取业务待办
 */
export async function getUserTodoBusiness({
  entry = null,
  exit = null,
  filterParamsFn = null,
  sucessCallback = null
} = {}) {
  try {
    entry && entry()
    const userInfo = Vue.getAcloudProvider().getUserInfo()
    const params = { query: { receiverId: userInfo.id, status: 0 } }
    const res = await getBusinessTodoList(filterParamsFn ? filterParamsFn(params) : params)
    sucessCallback && sucessCallback(res)
    return res
  } catch (e) {
    console.error('getUserTodoBusiness', e)
  } finally {
    exit && exit()
  }
}

/**
 * 获取我发起的审批
 */
export async function getSelfAuditList({
  entry = null,
  exit = null,
  filterParamsFn = null,
  sucessCallback = null
} = {}) {
  try {
    entry && entry()
    const userInfo = Vue.getAcloudProvider().getUserInfo()
    const params = {
      startUserId: userInfo.id,
      run: 0 // 0: 查询未完成的， 1: 已完成
    }
    const res = await getSelfAudit(filterParamsFn ? filterParamsFn(params) : params)
    sucessCallback && sucessCallback(res)
    return res
  } catch (e) {
    console.error('getUserTodoBusiness', e)
  } finally {
    exit && exit()
  }
}

/**
 * 获取流程的节点信息，其中 completed 字段： 2(未开始)、1（已完成）、0（进行中）
 */
export async function getProcessNodeDetail({
  entry = null,
  exit = null,
  filterParamsFn = null,
  businessId = '',
  sucessCallback = null
} = {}) {
  try {
    entry && entry()
    const res = await getCurrentProcess(businessId)
    const processData = res.data
    const userIds = []
    const groupList = []
    processData.forEach(item => {
      userIds.push(item.assignee)
      item.userName = item.userName || ''
      item.endTime = item.endTime || (item.completed !== 2 && '进行中') || ''
      item.durationInMillis = item.durationInMillis || (item.completed !== 2 && '进行中') || ''
      if (item.formData) {
        try {
          const formDataObj = JSON.parse(item.formData)
          item.opinions = formDataObj.opinions
          item.auditResult =
            formDataObj.reject === 'true' ? '审批不通过' : formDataObj.reject === 'false' ? '审批通过' : ''
        } catch (e) {
          console.error(e)
          throw new Error(e)
        }
      } else {
        item.opinions = ''
        item.auditResult = ''
      }
      // 如果groupId存在，则需要查询其节点对应的处理人；completed为1时，表示审批已完成
      if (item.groupId && item.completed !== 1) {
        try {
          const groupIdObj = JSON.parse(item.groupId)
          groupList.push({ ...groupIdObj, processTaskId: item.taskDefKey })
        } catch (e) {
          console.error(e)
          throw new Error(e)
        }
      }
      item.description = []
    })
    if (groupList.length) {
      const groupRes = await getProcessGroupPerson({
        assignGroup: groupList
      })
      const targetObj = groupRes.data || {}
      processData.forEach(item => {
        if (targetObj[item.taskDefKey] && item.groupId && item.completed !== 1) {
          item.userName = targetObj[item.taskDefKey].map(item => item.name).join('、')
        }
      })
    }
    const employRes = await getOrgEmployeesListBy({
      userIds,
      delete: true
    })
    processData.forEach(r => {
      employRes.data.some(e => {
        if (e.userId === r.assignee) {
          r.userName = e.name
          return true
        }
      })
    })
    sucessCallback && sucessCallback(res)
    return res
  } catch (e) {
    console.error(e)
  } finally {
    exit && exit()
  }
}

/**
 * 获取当前流程的信息列表
 * eg:   loadDataCurrent: () => {
 *           return getCurrentProcessList.call(this, {businessId: this.businessId})
 *       }
 * @param {String | Number} 业务ID
 */
export async function getCurrentProcessList({ businessId,newApi = false}) {
  let api = newApi?queryActiveTaskInfo:getCurrentProcess;
  return api(businessId).then(async res => {
    const processData = res.data
    const userIds = []
    const groupList = []
    processData.forEach(item => {
      userIds.push(item.assignee)
      item.userName = item.userName || ''
      item.endTime = item.endTime || (item.completed !== 2 && '进行中') || ''
      item.durationInMillis = item.durationInMillis || (item.completed !== 2 && '进行中') || ''
      if (item.formData) {
        try {
          const formDataObj = JosnBig.parse(item.formData)
          item.opinions = formDataObj.opinions
          // 处理结果修改为 后端直接返回
          // item.auditResult =
          //   formDataObj.reject === 'true' ? '审批不通过' : formDataObj.reject === 'false' ? '审批通过' : ''
          item.auditResult = item.processStatusName
        } catch (e) {
          console.error(e)
        }
      } else {
        item.opinions = ''
        item.auditResult = ''
      }
      // 如果groupId存在，则需要查询其节点对应的处理人；completed为1时，表示审批已完成
      if (item.groupId && item.completed !== 1) {
        try {
          const groupIdObj = JosnBig.parse(item.groupId)
          groupList.push({ ...groupIdObj, processTaskId: item.taskDefKey })
        } catch (e) {
          console.error(e)
        }
      }

      item.description = []
    })
    // 获取后面节点的处理人列表
    // 加入await保持所有接口返回后更新列表
    groupList.length &&
      await getProcessGroupPerson({
        assignGroup: groupList
      }).then(res => {
        const targetObj = res.data || {}
        processData.forEach(item => {
          if (targetObj[item.taskDefKey] && item.groupId && item.completed !== 1) {
            item.userName = targetObj[item.taskDefKey].map(item => item.name).join('、')
            // 返回处理人列表(流程监控选择审批人需要)
            item.userList = targetObj[item.taskDefKey]
            item.userId = targetObj[item.taskDefKey].map(item => item.userId)
          }
        })
      }).catch(e => {
        console.error(e)
      })
    // 加入await保持所有接口返回后更新列表
    if(userIds.length){
      return await getOrgEmployeesListBy({ userIds, delete: true }).then(employees => {
        this.flowRequesting = false
        processData.forEach(r => {
          employees.data.some(e => {
            if (e.userId === r.assignee) {
              r.userName = e.name
              return true
            }
          })
        })
        return res
      })
    }
  })
}

/**
 * 根据流程获取当前流程的信息列表
 * eg:   loadDataCurrent: () => {
 *           return getCurrentProcessInfo.call(this, {ProcessId: this.ProcessId})
 *       }
 * @param {String | Number} 流程ID
 */
export async function getCurrentProcessInfo({ procInstId }) {
  return getAllTasksByProcInst(procInstId).then(res => {
    const processData = res.data
    const userIds = []
    const groupList = []
    processData.forEach(item => {
      userIds.push(item.assignee)
      item.userName = item.userName || ''
      item.endTime = item.endTime || (item.completed !== 2 && '进行中') || ''
      item.durationInMillis = item.durationInMillis || (item.completed !== 2 && '进行中') || ''
      if (item.formData) {
        try {
          const formDataObj = JosnBig.parse(item.formData)
          item.opinions = formDataObj.opinions
          // 处理结果修改为 后端直接返回
          // item.auditResult =
          //   formDataObj.reject === 'true' ? '审批不通过' : formDataObj.reject === 'false' ? '审批通过' : ''
          item.auditResult = item.processStatusName
        } catch (e) {
          console.error(e)
        }
      } else {
        item.opinions = ''
        item.auditResult = ''
      }
      // 如果groupId存在，则需要查询其节点对应的处理人；completed为1时，表示审批已完成
      if (item.groupId && item.completed !== 1) {
        try {
          const groupIdObj = JosnBig.parse(item.groupId)
          groupList.push({ ...groupIdObj, processTaskId: item.taskDefKey })
        } catch (e) {
          console.error(e)
        }
      }

      item.description = []
    })
    // 获取后面节点的处理人列表
    groupList.length &&
      getProcessGroupPerson({
        assignGroup: groupList
      }).then(res => {
        const targetObj = res.data || {};
        processData.forEach(item => {
          let userObj = [];
          if (targetObj[item.taskDefKey] && item.groupId && item.completed !== 1) {
            item.userName = targetObj[item.taskDefKey].map(item => item.name).join('、')
            userObj.push({
              userName: targetObj[item.taskDefKey].map(item => item.name).join('、'),
              userId: targetObj[item.taskDefKey].map(item => item.id).join('、')
            })
            item.userObj = userObj
          }
        })
      }).catch(e => {
        console.error(e)
      })
    return getOrgEmployeesListBy({ userIds, delete: true }).then(employees => {
      this.flowRequesting = false
      processData.forEach(r => {
        employees.data.some(e => {
          if (e.userId === r.assignee) {
            r.userName = e.name
            return true
          }
        })
      })
      return res
    })
  })
}
